package com.alingrad.android.froyoengine;

import javax.microedition.khronos.opengles.GL10;

import android.content.Context;

import com.alingrad.android.froyoengine.graphics.RenderManager;
import com.alingrad.android.froyoengine.input.InputManager;
import com.alingrad.android.froyoengine.tree.MainLoop;
import com.alingrad.android.froyoengine.util.TextureLoader;

public class Game extends AllocationGuard {
	private boolean mReady;
	private boolean mRunning;
	private boolean mPaused;
	private GameThread mThread;
	private MainLoop mHead;
	private long mLastTimeMs;
	
	public static RenderManager sRenderManager;
	public static ResourceLibrary sResourceLibrary;
	public static InputManager sInputManager;
	
	public void load(GameRenderer renderer, GL10 gl) {
		sRenderManager = new RenderManager(renderer);
		sResourceLibrary = new ResourceLibrary();
		sInputManager = new InputManager();
		mHead.load(gl);
		start();
	}
	
	public Game(Context context, MainLoop loop) {
		super();
		mReady = false;
		mRunning = true;
		mPaused = false;
		mHead = loop;
		TextureLoader.prepare(context);
	}
	
	private class GameThread extends Thread {
		public GameThread() {
			super("Game Thread");
		}
		@Override
		public void run() {
			while (!mReady) {
				try {
					sleep(100);
				}catch (InterruptedException ex) {
				}
			}
			mLastTimeMs = System.currentTimeMillis();
			while (mRunning) {
				while (mPaused) {
					try {
						sleep(100);
					}catch (InterruptedException ex) {
					}
				}
				final long currentTime = System.currentTimeMillis();
				final long delta = currentTime - mLastTimeMs;
				sInputManager.update(delta);
				mHead.update(delta);
				sRenderManager.sync();
				mLastTimeMs = currentTime;
			}
		}
	}
	
	public void start() {
		mReady = true;
		mThread = new GameThread();
		mThread.start();
	}
	
	public void onPause() {
		mPaused = true;
	}
	
	public void onResume() {
		mPaused = false;
		mLastTimeMs = System.currentTimeMillis();
	}
	
	public void finish() {
		mRunning = false;
	}
	

}
